<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <title>Canvas Game Experiement - CodePen</title>
    <style>
      * {
          padding: 0;
          margin: 0;
      }

      html, body { width:100%; height:100%; } /* just to be sure these are full screen*/

      canvas { display:block; } /* To remove the scrollbars */

      #mycanvas {
        background: #eee;
        color: #222;
      }

    </style>
  </head>
  <body>
    <canvas id="mycanvas">Canvas doesn't work for you</canvas>
    <script>
    // requestAnim shim layer by Paul Irish
    window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / 30);
              };
    })();
    // add a listener for all touch events
    document.addEventListener("touchstart", handleStart, false); 
    document.addEventListener("touchend", handleEnd, false); 

    var canvas = document.getElementById("mycanvas"); // the game area
    canvas.height = Math.round(document.height); // height of the game
    canvas.width = Math.round(document.width); // width of the game
    var context = canvas.getContext("2d");    
    var h = Math.round(canvas.height);
    var w = Math.round(canvas.width);
    var gameTitle = "Ben's Game"; // temporary until title screen
    var d = "right"; // default direction
    var cw = 10; // shape of each body part in pixels
    var snake = []; // the constructor for the snake
    var ongoingTouches = []; // need this to keep track of touchEvents
    var touchX = touchY = 0;

    var GameController = function() {
      this.canvas = document.getElementById("mycanvas");
      this.context = canvas.getContext("2d");
      this.canvas.height = document.height; // height of the game
      this.canvas.width = document.width; // width of the game     
      this.gameTitle = "Sausage Dog v1";
    }

    var Snake = function() {
      this.snake = []; // the actual snake itself
      this.cw = 10; // dimensions for snake body part
      this.d = "right" // default direction the snake starts
    }

    function handleStart(evt) {
      evt.preventDefault();
      touchX = evt.touches[0].screenX;
      touchY = evt.touches[0].screenY;
    }

    function handleEnd(evt) {
      evt.preventDefault();      
      console.log("NEW touchstart: ("+ touchX + "," + touchY +")");
      console.log(w + "/ 2 = " + (w/2) );

      if (touchX < (w/2) ) {
        if(d != "down") {
          d = "down";
        } else {
          d = "left";
        }
      } else {
        if(d != "up") {
          d = "up";
        } else {
          d = "right";
        }
      } 
    }

    // snake constructor function
    function build_snake() {
      var length = 10; //Length of the snake
      for(var i = length-1; i>=0; i--)
      {
        //This will create a horizontal snake starting from the top left
        snake.push({x: i, y: 15});
      }
    }

    build_snake();
    create_food();
    animate();
    drawSnake();

  // set co-ordinates for the snake food
  function create_food()
  {
    food = {
      x: Math.round(Math.random()*(w-cw)/cw), 
      y: Math.round(Math.random()*(h-cw)/cw), 
    };
  }

function drawSnake() {
    //To avoid the snake trail we need to paint the BG on every frame
    //Lets paint the canvas now
    context.fillStyle = "white";
    context.fillRect(0, 0, w, h);
    
    //The movement code for the snake to come here.
    //The logic is simple
    //Pop out the tail cell and place it infront of the head cell
    var nx = snake[0].x;
    var ny = snake[0].y;
    //These were the position of the head cell.
    //We will increment it to get the new head position
    //Lets add proper direction based movement now
    if(d == "right") nx++;
    else if(d == "left") nx--;
    else if(d == "up") ny--;
    else if(d == "down") ny++;
    
    w = Math.round(w);
    h = Math.round(h);
    //Lets add the game over clauses now
    //This will restart the game if the snake hits the wall
    if(nx == -1 || nx == Math.round(w/cw) || ny == -1 || ny == Math.round(h/cw) || check_collision(nx, ny, snake))
    {
      //restart game
      console.log(nx + " : " + ny + " | w/cw = " + Math.round(w/cw));
      console.log('game over'); 
      //Lets organize the code a bit now.
      return;
    }
    
    //Lets write the code to make the snake eat the food
    //The logic is simple
    //If the new head position matches with that of the food,
    //Create a new head instead of moving the tail
    if(nx == food.x && ny == food.y) {
      var tail = {x: nx, y: ny};
      create_food();
    } else {
      var tail = snake.pop(); //pops out the last cell
      tail.x = nx; tail.y = ny;
    }
    snake.unshift(tail); //puts back the tail as the first cell     
        
    for(var i = 0; i < snake.length; i++)
    {
      var c = snake[i];
      //Lets paint 10px wide cells
      paint_cell(c.x, c.y);
    }
  //Lets paint the food
  paint_cell(food.x, food.y);
  requestAnimFrame(draw);
} 

function check_collision(x, y, array)
  {
    //This function will check if the provided x/y coordinates exist
    //in an array of cells or not
    for(var i = 0; i < array.length; i++)
    {
      if(array[i].x == x && array[i].y == y)
       return true;
    }
    return false;
  }

//Lets first create a generic function to paint cells
function paint_cell(x, y)
{
  context.fillStyle = "blue";
  context.fillRect(x*10, y*10, 10, 10);
}

function drawTitle(gameTitle) {
  context.font = "20px Georgia";
  context.fillText(gameTitle, 10, 25);
}

function animate() {
    requestAnimFrame(draw);
}

function draw() {
  // clear
  //context.clearRect(0, 0, canvas.width, canvas.height);

  // draw stuff
  drawSnake();
  drawTitle(gameTitle);
}


function move_snake(key) {
  if(key == "37" && d != "right") d = "left";
  else if(key == "38" && d != "down") d = "up";
  else if(key == "39" && d != "left") d = "right";
  else if(key == "40" && d != "up") d = "down";
}

window.onkeydown = function(e) {
  move_snake(e.keyCode);
} 
  </script>
  </body>
</html>
